package com.okq.dao;

import com.okq.dao.base.Impl.BaseDao;
import com.okq.entity.Role;
import com.okq.util.page.Page;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Repository;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 描述 : 角色Dao
 * 作者 : zdl
 * 日期 : 2017/6/28 13:45
 */
@Repository
public class RoleDao extends BaseDao {

    public void saveRole(Role role) {
        super.save(role);
    }

    public void deleteRole(Role role){super.delete(role);}

    public void updateRole(Role role) {
        super.update(role);
    }

    public void saveOrUpdateRole(Role role) {
        super.saveOrUpdate(role);
    }

    public Role getRoleById(String id) {
        return (Role) super.get(Role.class, id);
    }

    public List<Role> listAllRole() {
        String hql = "FROM Role WHERE isDelete=0";
        return super.find(hql);
    }

    /**
     * 分页查询
     *
     * @param page 分页
     * @param role 角色查询
     * @return page
     */
    public Page<Role> pageByRole(Page<Role> page, Role role) {
        StringBuilder sb = new StringBuilder();
        sb.append("FROM Role r WHERE r.isDelete = 0");
        if (role != null) {
            Map<String, Object> param = new HashMap<>();
            String roleName = role.getRoleName();
            if (StringUtils.isNotBlank(roleName)) {
                sb.append(" AND r.roleName LIKE ?1 ");
                param.put("1", "%" + roleName + "%");
            }

            Integer roleType = role.getRoleType();
            if (roleType != null && roleType >= 0) {
                sb.append(" AND r.roleType = ?2 ");
                param.put("2", roleType);
            }
            sb.append(" ORDER BY r.createTime DESC ");
            return super.findByPage(page, sb.toString(), param);
        }
        return page;
    }

    /**
     * 根据角色名称查询角色信息
     *
     * @param roleName 角色名称
     * @return 角色对象
     */
    public Role getRoleByName(String roleName) {
        String hql = "FROM Role WHERE isDelete = 0 AND roleName = '" + roleName + "'";
        return (Role) super.get(hql);
    }

}
